<?php
namespace app\ws\controller\workerman;
use app\common\model\redis\RedisModel;
use app\api\controller\External;
use think\worker\Server;
use Workerman\Lib\Timer;
use app\workerman\Events;
class Worker extends Server
{
    protected $socket; // 地址
    protected $count = ''; // 进程数
    protected $worker;
    protected $name;
    protected $uidConnections = [];
    public function __construct()
    {
        $this->socket = config("worker_server.socket");
        $this->count = config("worker_server.count");
        parent::__construct();
        $this->worker->onWorkerStart = function($worker)
        {
            // 收到信息
            $worker->onMessage = function($connection, $data) use($worker) {
                $this->handle($worker, $connection, $data);
            };
            // 所有定时器相关的初始化
            $this->timerInit($worker);
        };
    }

    /**
     * 所有定时器相关的初始化
     * @param $worker
     */
    public function timerInit($worker){
        $this->timer($worker);
    }
    /**
     * 定时器
     * @param $worker
     */
    public function timer($worker)
    {
        try{
            $RedisModel = new RedisModel();
            Timer::add(1, function()use($worker)
            {
                var_dump(22);

            });
        }catch (\Exception $e){
            logWrite('addHotWords', $e->getMessage(), __FILE__ );
            return returnResult(config("config.code.error"),config("config.describe.error"));
        }
    }

    /**
     * 参数处理
     * @param $worker
     * @param $connection
     * @param $data
     */
    protected function handle($worker, $connection, $data) {
        $data = json_decode($data, true);
        $action = $data['action']; // 指定调用方法
        $params = $data['params']; // 参数
        switch ($action) {
            case 'login':
//                $this->login($worker, $connection, $params);
//                var_dump(111);
                break;
        }
    }

    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
        if(isset($connection->id)) {
            // 连接断开时删除映射
            unset($this->worker->uidConnections[$connection->id]);
        }
    }
    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        var_dump('当客户端的连接上发生错误时触发');
    }
    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
        echo "new connection from id " . $connection->id . "\n";
        $this->worker->uidConnections[$connection->id] = $connection;
        var_dump(count($this->worker->uidConnections));
    }
    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        var_dump('每个进程启动');
    }
    /**
     * 给指定用户发消息
     * @param $name 推送的action名称
     * @param $res 推送的结果(基于operationRes()的返回结果)
     */
    private function sendMsgByConnectId($worker, $connectIdArr, $res,$name='') {
        if(!empty($connectIdArr)){
            for($i=0;$i<count($connectIdArr);$i++){
                if(isset($worker->uidConnections[$connectIdArr[$i]['connect_id']])) {
                    $connection = $worker->uidConnections[$connectIdArr[$i]['connect_id']];
                    $connection->send(returnRst($res,200,'ok！',$name));
                }
            }
        }
    }

    /**
     * 给所有用户发消息
     * @param $name 推送的action名称
     * @param $res 推送的结果(基于operationRes()的返回结果)
     */
    private function sendMsgToAll($worker, $name='', $res) {
        foreach ($worker->uidConnections as $key => $val) {
            $worker->uidConnections[$key]->send(returnRst($res,200,'ok'));
        }
    }
    /**
     * 关闭ID连接
     * @param $worker
     * @param $connect_id
     */
    private function close($worker, $connect_id) {
        try{
            $connection = $worker->uidConnections[$connect_id];
            $connection->close();
        }catch (\Exception $e){

        }
    }
    /**
     * 定时广播用户
     * @param $worker
     */
    public function timedBroadcast($worker,$time)
    {
        Timer::add($time, function()use($worker)
        {
            // 遍历当前进程所有的客户端连接，发送当前服务器的时间
            foreach($worker->connections as $connection)
            {
                $connection->send(time());
            }
        });
    }

}
